package com.badibadi.fragment;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.tsz.afinal.FinalBitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Fragment;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.badibadi.activity.AfterLandingActivity;
import com.badibadi.activity.MyDataActivity;
import com.badibadi.activity.PicturePreviewActivity;
import com.badibadi.activity.SeeOtherPeopleSpaceActivity;
import com.badibadi.activity.UpPicturesActivity;
import com.badibadi.fragment.AfterLandingMessageItem05.ViewHolder;
import com.badibadi.fragment.AfterLandingMessageItem05.XListView1Adapter____1;
import com.badibadi.infos.BrowseAllPhoto_Model;
import com.badibadi.infos.Pre_message_total;
import com.badibadi.infos.Results;
import com.badibadi.mytools.BitmapHelp;
import com.badibadi.mytools.CalendarTools;
import com.badibadi.mytools.Constants;
import com.badibadi.mytools.DisplayUtil;
import com.badibadi.mytools.IOUtils;
import com.badibadi.mytools.JSONUtils;
import com.badibadi.mytools.MyThreadTool;
import com.badibadi.mytools.Utils;
import com.badibadi.uniclubber.R;
import com.libjph.util.StringUtil;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.view.my_view.XListView;
import com.view.my_view.XListView.IXListViewListener;

///**
//* 第七个fragment 上传
//* @author Administrator getUid()
//*shangchuan
//*/
public class AfterLandingMessageItem06 extends BaseAppFragment implements
		IXListViewListener {
	// TODO Auto-generated method stub
	private String TAG = "AfterLandingMessageItem00";
	private XListView1Adapter____1 x1Adapter;
	private XListView xListView1;
	private int Page;
	private Results results, results2;
	private List<Pre_message_total> mList;
	List<Pre_message_total> list;
	FinalBitmap finalBitmap;
	private int pageNum = 6;
	// private DisplayImageOptions options;
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				Utils.ExitPrgress(getActivity());

				try {
					onLoad();
					Utils.showMessage(getActivity(),
							getResources().getString(R.string.l_net_error));
				} catch (Exception e) {
				}

				break;
			case 2:
				Utils.ExitPrgress(getActivity());
				try {
					mList.addAll(list);
					x1Adapter.notifyDataSetChanged();
					onLoad();
				} catch (Exception e) {
					// TODO: handle exception
				}

				break;
			case 3:
				Utils.ExitPrgress(getActivity());

				try {
					onLoad();
					Utils.showMessage(getActivity(),
							getResources().getString(R.string.l_xa10));
				} catch (Exception e) {
					// TODO: handle exception
					// throw new NullPointerException("getActivity() is Null");
				}
				break;
			case 4:
				Utils.ExitPrgress(getActivity());
				try {
					Utils.showMessage(getActivity(), results2.getRetmsg());
				} catch (Exception e) {
					// TODO: handle exception
					// throw new NullPointerException("getActivity() is Null");
				}
			default:
				break;
			}
		}
	};
	private String uid;
	BitmapHelp bitmapHelp;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mList = new ArrayList<Pre_message_total>();
		x1Adapter = new XListView1Adapter____1();
		bitmapHelp = new BitmapHelp();
		// options = new DisplayImageOptions.Builder()
		// .showStubImage(R.drawable.ic_stub)
		// .showImageForEmptyUri(R.drawable.noimage)
		// .showImageOnFail(R.drawable.noimage).cacheInMemory()
		// .cacheOnDisc().displayer(new RoundedBitmapDisplayer(5)).build();
		finalBitmap = FinalBitmap.create(getActivity());
		finalBitmap.configLoadfailImage(R.drawable.noimage);
		finalBitmap.configLoadingImage(R.drawable.noimage);
		// 磁盘缓存路径
		finalBitmap.configDiskCachePath(IOUtils.getSaveObjectPath(
				getActivity(), "NoticActivity"));
		finalBitmap.configDiskCacheSize(10 * 1024);
		finalBitmap.configMemoryCacheSize(4);
		uid = getArguments().getString("uid");
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.after_landing_freinds00_1, null);
		InitMyXListView1(view);
		return view;
	}

	public void InitMyXListView1(View view) {
		Page = 0;
		Constants.Invite_handler = mHandler;
		xListView1 = (XListView) view
				.findViewById(R.id.after_landing_friends00_xlistView);
		xListView1.setXListViewListener(this);
		xListView1.setPullLoadEnable(true);
		xListView1.setPullRefreshEnable(true);
		xListView1.setAdapter(x1Adapter);
		xListView1.startLoadMore();
	}

	private void LoadingMessage(final int page) {
		MyThreadTool.fixedThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				list = new ArrayList<Pre_message_total>();
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("uid", uid);
				map.put("type", "message_uploadimg");
				map.put("page", page);

				map.put("pageNum", pageNum);
//				   
				String invite_content = Utils.sendRequest(map,
						Constants.BadiUrl + "message_total");
				//    
				if (invite_content != null) {
					results = Utils.checkResult_NNN(getActivity(),
							invite_content);
					if (results != null && !results.getRetmsg().equals("null")) {
//						   
						try {
							list = JSONUtils.getListByJsonString(
									results.getRetmsg(),
									Pre_message_total.class);

							mHandler.sendEmptyMessage(2);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							   
							mHandler.sendEmptyMessage(3);
						}
					} else {
						if (page > 1) {
							--Page;
						} else {
							Page = 1;
						}
						mHandler.sendEmptyMessage(3);
					}
				} else {
					if (page > 1) {
						--Page;
					} else {
						Page = 1;
					}
					mHandler.sendEmptyMessage(1);
				}

			}
		});
	}

	protected void onLoad() {
		xListView1.stopRefresh();
		xListView1.stopLoadMore();
		xListView1.setRefreshTime(""+getResources().getString(R.string.ganggang));
	}

	class XListView1Adapter____1 extends BaseAdapter {
		// private DisplayImageOptions options;

		public XListView1Adapter____1() {
			// options = new DisplayImageOptions.Builder()
			// .showStubImage(R.drawable.ic_stub)
			// .showImageForEmptyUri(R.drawable.noimage)
			// .showImageOnFail(R.drawable.noimage).cacheInMemory()
			// .cacheOnDisc().displayer(new RoundedBitmapDisplayer(0))
			// .build();
		}

		@Override
		public int getCount() {

			return mList.size();
		}

		@Override
		public Object getItem(int position) {
			return mList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {// name
			// int imageWH = 55;
			LayoutInflater mInflater = LayoutInflater.from(getActivity());

			ViewHolder holder;

			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.shangchuan, parent,
						false);
				holder = new ViewHolder();
				holder.nickName = (TextView) convertView
						.findViewById(R.id.nickName);
				holder.nickName2 = (TextView) convertView
						.findViewById(R.id.nickName2);
				// holder.name=(TextView)convertView.findViewById(R.id.name);
				holder.head = (ImageView) convertView.findViewById(R.id.head);
				holder.time = (TextView) convertView.findViewById(R.id.time);
				holder.num = (TextView) convertView.findViewById(R.id.num);
				holder.name = (TextView) convertView.findViewById(R.id.name);
				holder.table = (TextView) convertView.findViewById(R.id.table);
				holder.name_title_content = (TextView) convertView
						.findViewById(R.id.name_title_content);
				holder.message = (TextView) convertView
						.findViewById(R.id.message);
				holder.iv_0 = (ImageView) convertView.findViewById(R.id.iv_0);
				holder.iv_1 = (ImageView) convertView.findViewById(R.id.iv_1);
				holder.iv_2 = (ImageView) convertView.findViewById(R.id.iv_2);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			holder.iv_0.setVisibility(View.VISIBLE);
			holder.iv_1.setVisibility(View.VISIBLE);
			holder.iv_2.setVisibility(View.VISIBLE);

			String[] imgpath;
			String[] imgid;

			if (!StringUtil.isNullOrEmpty(mList.get(position).getImgPath())
					&& !StringUtil.isNullOrEmpty(mList.get(position).getIid())) {
				imgpath = mList.get(position).getImgPath().split(",");
				imgid = mList.get(position).getIid().split(",");
				if (imgpath.length <= imgid.length) {
					if (imgpath.length >= 3) {
						new BitmapHelp().displayImage(getActivity(),
								holder.iv_0, Constants.BadiDownImgUrl + "/"
										+ imgpath[0] + Constants.App9block);
						// bitmapHelp.displayImage(getActivity(), holder.iv_0,
						// Constants.BadiDownImgUrl + "/" + imgpath[0]
						// + Constants.App9block);
						// ImageLoader.getInstance().displayImage(
						// Constants.BadiDownImgUrl + "/" + imgpath[1]
						// + Constants.App9block, holder.iv_1,
						// options);
						new BitmapHelp().displayImage(getActivity(),
								holder.iv_1, Constants.BadiDownImgUrl + "/"
										+ imgpath[1] + Constants.App9block);
						// bitmapHelp.displayImage(getActivity(), holder.iv_1,
						// Constants.BadiDownImgUrl + "/" + imgpath[1]
						// + Constants.App9block);
						// ImageLoader.getInstance().displayImage(
						// Constants.BadiDownImgUrl + "/" + imgpath[2]
						// + Constants.App9block, holder.iv_2,
						// options);
						new BitmapHelp().displayImage(getActivity(),
								holder.iv_2, Constants.BadiDownImgUrl + "/"
										+ imgpath[2] + Constants.App9block);
						// bitmapHelp.displayImage(getActivity(), holder.iv_2,
						// Constants.BadiDownImgUrl + "/" + imgpath[2]
						// + Constants.App9block);
						List<BrowseAllPhoto_Model> AllPhoto_Models = new ArrayList<BrowseAllPhoto_Model>();
						for (int i = 0; i < imgpath.length; i++) {
							BrowseAllPhoto_Model br = new BrowseAllPhoto_Model();
							if (!StringUtil.isNullOrEmpty(imgid[i])) {
								br.setId(imgid[i]);
								br.setPath(imgpath[i]);
								AllPhoto_Models.add(br);
							}
						}
						openImageClick(holder.iv_0, holder.iv_1, holder.iv_2,
								AllPhoto_Models, 3);
					} else if (imgpath.length == 2) {
						// ImageLoader.getInstance().displayImage(
						// Constants.BadiDownImgUrl + "/" + imgpath[0]
						// + Constants.App9block, holder.iv_0,
						// options);
						new BitmapHelp().displayImage(getActivity(),
								holder.iv_0, Constants.BadiDownImgUrl + "/"
										+ imgpath[0] + Constants.App9block);
						// bitmapHelp.displayImage(getActivity(), holder.iv_0,
						// Constants.BadiDownImgUrl + "/" + imgpath[0]
						// + Constants.App9block);
						// ImageLoader.getInstance().displayImage(
						// Constants.BadiDownImgUrl + "/" + imgpath[1]
						// + Constants.App9block, holder.iv_1,
						// options);
						new BitmapHelp().displayImage(getActivity(),
								holder.iv_1, Constants.BadiDownImgUrl + "/"
										+ imgpath[1] + Constants.App9block);
						// bitmapHelp.displayImage(getActivity(), holder.iv_1,
						// Constants.BadiDownImgUrl + "/" + imgpath[1]
						// + Constants.App9block);
						List<BrowseAllPhoto_Model> AllPhoto_Models = new ArrayList<BrowseAllPhoto_Model>();
						for (int i = 0; i < imgpath.length; i++) {
							BrowseAllPhoto_Model br = new BrowseAllPhoto_Model();
							if (!StringUtil.isNullOrEmpty(imgid[i])) {
								br.setId(imgid[i]);
								br.setPath(imgpath[i]);
								AllPhoto_Models.add(br);
							}
						}
						openImageClick(holder.iv_0, holder.iv_1, holder.iv_2,
								AllPhoto_Models, 2);

						closeImageClick(holder.iv_0, holder.iv_1, holder.iv_2,
								1);
					} else if (imgpath.length == 1) {
						// ImageLoader.getInstance().displayImage(
						// Constants.BadiDownImgUrl + "/" + imgpath[0]
						// + Constants.App9block, holder.iv_0,
						// options);
						new BitmapHelp().displayImage(getActivity(),
								holder.iv_0, Constants.BadiDownImgUrl + "/"
										+ imgpath[0] + Constants.App9block);
						// bitmapHelp.displayImage(getActivity(), holder.iv_0,
						// Constants.BadiDownImgUrl + "/" + imgpath[0]
						// + Constants.App9block);
						List<BrowseAllPhoto_Model> AllPhoto_Models = new ArrayList<BrowseAllPhoto_Model>();
						for (int i = 0; i < imgpath.length; i++) {
							BrowseAllPhoto_Model br = new BrowseAllPhoto_Model();
							if (!StringUtil.isNullOrEmpty(imgid[i])) {
								br.setId(imgid[i]);
								br.setPath(imgpath[i]);
								AllPhoto_Models.add(br);
							}
						}
						openImageClick(holder.iv_0, holder.iv_1, holder.iv_2,
								AllPhoto_Models, 1);

						closeImageClick(holder.iv_0, holder.iv_1, holder.iv_2,
								2);
					} else {
						closeImageClick(holder.iv_0, holder.iv_1, holder.iv_2,
								3);
					}
				}

			} else {

				closeImageClick(holder.iv_0, holder.iv_1, holder.iv_2, 3);
			}

			// //好友回复的消息
			holder.name.setText("" + mList.get(position).getName());
			holder.name.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if (mList.get(position).getIid() != null) {
						Intent intent = new Intent(getActivity(),
								UpPicturesActivity.class);
						intent.putExtra("photoid", mList.get(position).getPid());
						startActivity(intent);
					}
				}
			});
			// 昵称
			holder.nickName.setText("" + mList.get(position).getNickName());
			holder.nickName2.setText("" + mList.get(position).getNickName());
			// 头像
			try {
				if (!StringUtil.isNullOrEmpty(mList.get(position).getHead())) {
					finalBitmap.display(holder.head, Constants.BadiDownImgUrl
							+ "/" + mList.get(position).getHead()
							+ Constants.appPhoto4img);
					// bitmapHelp.displayImage(getActivity(), holder.head,
					// Constants.BadiDownImgUrl
					// + "/" +
					// mList.get(position).getHead()+Constants.appPhoto4img);
				} else {
					holder.head.setImageResource(R.drawable.noimage);
				}

			} catch (Exception e) {
				// TODO: handle exception
			}

			// 发布时间
			try {
				holder.time.setText(""
						+ CalendarTools.getTimeChangeToString(getActivity(),
								mList.get(position).getTime()));
			} catch (Exception e) {
				// TODO: handle exception
			}
			// 上传图片
			holder.num.setText("" + mList.get(position).getNum());
			// //记录名称
			// // holder.name.setText(""+mList.get(position).getName());
			// holder.name_title_content.setText(""+mList.get(position).getName());
			// // //1是回复，0是评论
			// if(mList.get(position).getType().equals("photo_img"))
			// {
			// holder.table.setText("照片");
			// }
			// else if(mList.get(position).getType().equals("humor_trends"))
			// {
			// holder.table.setText("动态");
			// }else if(mList.get(position).getType().equals("record"))
			// {
			// holder.table.setText("记录");
			// }
			holder.head.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if (!StringUtil.isNullOrEmpty(mList.get(position).getUid())) {
						if (mList.get(position).getUid()
								.equals(Utils.getUid(getActivity()))) {
							Intent intent = new Intent(getActivity(),
									MyDataActivity.class);
							startActivity(intent);
						} else {
							Intent intent = new Intent(getActivity(),
									SeeOtherPeopleSpaceActivity.class);
							intent.putExtra("friend_id", mList.get(position)
									.getUid());
							startActivity(intent);
						}
					}
				}
			});
			holder.nickName.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if (!StringUtil.isNullOrEmpty(mList.get(position).getUid())) {
						if (mList.get(position).getUid()
								.equals(Utils.getUid(getActivity()))) {
							Intent intent = new Intent(getActivity(),
									MyDataActivity.class);
							startActivity(intent);
						} else {
							Intent intent = new Intent(getActivity(),
									SeeOtherPeopleSpaceActivity.class);
							intent.putExtra("friend_id", mList.get(position)
									.getUid());
							startActivity(intent);
						}
					}
				}
			});
			holder.nickName2.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if (!StringUtil.isNullOrEmpty(mList.get(position).getUid())) {
						if (mList.get(position).getUid()
								.equals(Utils.getUid(getActivity()))) {
							Intent intent = new Intent(getActivity(),
									MyDataActivity.class);
							startActivity(intent);
						} else {
							Intent intent = new Intent(getActivity(),
									SeeOtherPeopleSpaceActivity.class);
							intent.putExtra("friend_id", mList.get(position)
									.getUid());
							startActivity(intent);
						}
					}
				}
			});
			return convertView;
		}
	}

	/**
	 * 开启的数量（从前往后）
	 * 
	 * @param iv_0
	 * @param iv_1
	 * @param iv_2
	 * @param AllPhoto_Models
	 * @param startNum
	 */
	private void openImageClick(ImageView iv_0, ImageView iv_1, ImageView iv_2,
			final List<BrowseAllPhoto_Model> AllPhoto_Models, int startNum) {
		if (startNum > 0) {
			iv_0.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Intent intent = new Intent(getActivity(),
							PicturePreviewActivity.class);
					intent.putExtra("picture_list",
							(Serializable) AllPhoto_Models);
					intent.putExtra("picture_postion", 0);
					getActivity().startActivity(intent);
				}
			});
		}
		if (startNum > 1) {
			iv_1.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Intent intent = new Intent(getActivity(),
							PicturePreviewActivity.class);
					intent.putExtra("picture_list",
							(Serializable) AllPhoto_Models);
					intent.putExtra("picture_postion", 1);
					getActivity().startActivity(intent);
				}
			});
		}
		if (startNum > 2) {
			iv_2.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Intent intent = new Intent(getActivity(),
							PicturePreviewActivity.class);
					intent.putExtra("picture_list",
							(Serializable) AllPhoto_Models);
					intent.putExtra("picture_postion", 1);
					getActivity().startActivity(intent);
				}
			});
		}

	}

	/**
	 * 把imageView的点击事件去掉（从后往前）
	 * 
	 * @param iv_0
	 * @param iv_1
	 * @param iv_2
	 * @param closeNum
	 *            需要关闭的imageView数量
	 */
	private void closeImageClick(ImageView iv_0, ImageView iv_1,
			ImageView iv_2, int closeNum) {

		if (closeNum > 0) {
			iv_2.setVisibility(View.INVISIBLE);
			iv_2.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {

				}
			});
		}
		if (closeNum > 1) {
			iv_1.setVisibility(View.INVISIBLE);

			iv_1.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {

				}
			});

		}
		if (closeNum > 2) {
			iv_0.setVisibility(View.INVISIBLE);
			iv_0.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {

				}
			});
		}

	}

	static class ViewHolder {
		public ImageView iv_2;
		public ImageView iv_1;
		public ImageView iv_0;
		// 创立
		public ImageView head;// 用户的头像
		public TextView nickName;// 用户的昵称
		public TextView nickName2;// 用户的昵称
		public String uid;// 用户id
		public String firends;// 共同的好友
		public TextView motto;// 用户个性说明
		public String cid;// 俱乐部的id
		public TextView name;// 俱乐部的名字
		public TextView typeName;// 俱乐部的类型
		public TextView time;// 操作时间
		public String is_show;// 是否查看过 0：未查看，1：已查看
		// praise 的属性 赞
		// public String firends;//共同的好友
		// public String head ;//用户的头像
		// public String nickName ;//用户的昵称
		// public String uid ;//用户id
		// public String time ;//操作时间
		public TextView type;// 被赞的类型 activity photo_img humor_trends photo
								// record_article club
		public String id;// 被赞的记录id
		public TextView name_title_content;// 被赞的记录名字
		// public String is_show;//是否查看过 0：未查看，1：已查看

		// %%%%% discuss 的属性评论

		public TextView is_reply;// 1表示回复评论 0表示评论
		// public String id;//回复我的 评论的id
		public TextView message;// 回复内容
		// public String firends;//共同的好友
		// public String head ;//用户的头像
		// public String nickName ;//用户的昵称
		// public String uid ;//用户id
		// public String time ;//操作时间
		// public String is_show;//是否查看过 0：未查看，1：已查看
		// 第二种 评论
		// public String is_reply;//1表示回复评论 0表示评论
		public TextView table;// 评论的什么类型 activity photo_img humor_trends photo
								// record_article club
		// public String name_title_content;//对应类型的记录名字
		// public String id;//对应类型的记录id
		// public String firends;//共同的好友
		// public String head ;//用户的头像
		// public String nickName ;//用户的昵称
		// public String uid ;//用户id
		// public String time ;//操作时间
		// public String is_show;//是否查看过 0：未查看，1：已查看
		public String umessage;// 我的评论内容

		// user_collect 属性
		// public $type;//收藏的类型 photo_img record humor_trends
		// public $id;//id
		// public $name;//收藏的类型对应记录的名字
		// public $firends;//共同的好友
		// public $head ;//用户的头像
		// public $nickName ;//用户的昵称
		// public $uid ;//用户id
		// public $time ;//操作时间
		// public $is_show;//是否查看过 0：未查看，1：已查看

		// message_uploadimg 属性
		public TextView num;// 上传多少张照片
		public String iid;// 对应的id 格式 id1,id2,...
		// public String firends ;//共同的好友
		// public String head ;//用户的头像
		// public String nickName ;//用户的昵称
		// public String uid ;//用户id
		// public String time ;//操作时间
		// public String is_show;//是否查看过 0：未查看，1：已查看
		// public String name;

	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		Page = 1;
		mList = new ArrayList<Pre_message_total>();
		LoadingMessage(Page);
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		// Utils.showPrgress(getActivity());
//		   
		Page = Page + 1;
		LoadingMessage(Page);
	}
}